//
//  MyselfViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/20.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "MyselfViewController.h"
#import "LoginViewController.h"
#import "BlackManager.h"
#import "SetBlack.h"
#import "CollectionViewController.h"
#import "ManagerViewController.h"
#import "OtherLoginViewController.h"
#import <UIImageView+WebCache.h>
#import "AboutViewController.h"
//#import "ScanViewController.h"
//识别二维码头文件
#import "Scan_VC.h"
#import "ErWebViewController.h"
//#import "ZBarSDK.h"
//发邮件
#import <MessageUI/MFMailComposeViewController.h>
@interface MyselfViewController ()<UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSArray *dataArrtop;
@property (nonatomic, retain)NSArray *dataArdown;
@property (nonatomic, assign)BOOL login;
@property (nonatomic, assign)CGFloat j;
@property (nonatomic, retain)UIView *topview;//上面灰色的区域
//@property (nonatomic, retain)UIButton *otherBtn;//其他方式登陆和姓名
//@property (nonatomic, strong)UIButton *person;//头像
@property (nonatomic, retain)UIImageView *headImg;//头像图片
@property (nonatomic, retain)NSTimer *time;
@property (nonatomic, assign)BOOL i;
@end

@implementation MyselfViewController

-(void)dealloc
{
//    [_tableView release];
    [_dataArrtop release];
    [_dataArdown release];
    [_topview release];
//    [_otherBtn release];
    [_headImg release];
    [_time release];
    //本地推送
    [_time invalidate];
    _time = nil;
    [[UIApplication sharedApplication]cancelAllLocalNotifications];
    [super dealloc];
}
//-(void)viewWillAppear:(BOOL)animated
//{
//    NSLog(@"将要出现");
//    NSLog(@"%@", NSHomeDirectory());
//     BOOL login = [[NSUserDefaults standardUserDefaults]boolForKey:@"register"];
//    if (login) {
//        //姓名
//        NSString *nameStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
//        [_otherBtn setTitle:nameStr forState:UIControlStateNormal];
//        //头像
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        BOOL sanFang = [[NSUserDefaults standardUserDefaults]boolForKey:@"OtherLogin"];
//        //判断是否是三方登录的
//        if (sanFang) {
//            NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"img"];
//            [_headImg sd_setImageWithURL:[NSURL URLWithString:str]];
//        }else if (_headImg) {
//            NSString *picturePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"picture.a"];
//            NSMutableArray *pictureArr = [NSKeyedUnarchiver unarchiveObjectWithFile:picturePath];
//            NSNumber *i = [[NSUserDefaults standardUserDefaults]objectForKey:@"index"];
//            NSInteger index = i.intValue;
//            NSString *str = [pictureArr objectAtIndex:index];
//            if (str.length == 1) {
//                [_headImg setImage:[UIImage imageNamed:@"qiaoba.png"]];
//            }else if ([userDefaults dataForKey:@"img"]) {
//                [_headImg setImage:[UIImage imageWithData:[userDefaults dataForKey:@"img"]]];
//                }
//        
//        }
//    }else{
//        //设置按钮
//        [_otherBtn setTitle:@"更多登录方式 >" forState:UIControlStateNormal];
//        _otherBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
//        [_otherBtn setBackgroundColor:[UIColor lightGrayColor]];
//        _otherBtn.layer.cornerRadius = 12;
//        _otherBtn.clipsToBounds = YES;
//        //设置头像为默认图片
//        [_headImg setImage:[UIImage imageNamed:@"qiaoba.png"]];
//         }
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的";
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-back"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)] autorelease];
    
    //tableView
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Mcell"];
    [_tableView release];
    //tableView上面View
    self.topview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3 - 20 )];
    self.headImg = [[UIImageView alloc]initWithFrame:CGRectMake(self.topview.frame.size.width / 10 * 4, self.topview.frame.size.height / 6, self.topview.frame.size.width / 4, self.topview.frame.size.width / 4)];
    _headImg.center = CGPointMake(_topview.frame.size.width / 2, _topview.frame.size.height / 2);
    _headImg.userInteractionEnabled = YES;
    _headImg.layer.cornerRadius = self.view.frame.size.width / 8;
    _headImg.clipsToBounds = YES;
    //设置头像图片
    [_headImg setImage:[UIImage imageNamed:@"qiaoba.png"]];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //判断 如果有(用保存的图片替换原来的头像图片)
    if ([userDefaults dataForKey:@"img"]) {
        [_headImg setImage:[UIImage imageWithData:[userDefaults dataForKey:@"img"]]];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeAction)];
    [_headImg addGestureRecognizer:tap];
    [self.topview addSubview:_headImg];
    
    //判断是否登陆改变页面上部样式
    self.login = [[NSUserDefaults standardUserDefaults]boolForKey:@"register"];
    //创建其他登陆按钮
//    self.otherBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    _otherBtn.frame = CGRectMake(self.topview.frame.size.width / 3 + 3, _headImg.frame.origin.y + _headImg.frame.size.height + 5, self.topview.frame.size.width / 3, 25);
//    [self.topview addSubview:_otherBtn];
//    [_headImg release];
    [_topview release];
//    if (_login) {
//        //如果登陆了下方是用户名的lable
//        NSString *nameStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
//        [_otherBtn setTitle:nameStr forState:UIControlStateNormal];
//        _otherBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
//        [_otherBtn setBackgroundColor:[UIColor lightGrayColor]];
//        _otherBtn.layer.cornerRadius = 12;
//        _otherBtn.clipsToBounds = YES;
//    }else{
//    //其他登录方式按钮
//        //设置按钮
//        [_otherBtn setTitle:@"更多登录方式 >" forState:UIControlStateNormal];
//        _otherBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
//        [_otherBtn setBackgroundColor:[UIColor lightGrayColor]];
//        //按钮的点击事件
//        [_otherBtn addTarget:self action:@selector(otherAction) forControlEvents:UIControlEventTouchUpInside];
//        _otherBtn.layer.cornerRadius = 12;
//        _otherBtn.clipsToBounds = YES;
//    }
    _tableView.tableHeaderView = _topview;
    
    self.dataArrtop = @[@"收藏", @"夜间模式", @"清除缓存"];
    self.dataArdown = @[@"扫一扫", @"关于应用", @"意见反馈"];
}
//其他登录方式
-(void)otherAction
{
    BOOL login = [[NSUserDefaults standardUserDefaults]boolForKey:@"register"];
    if (login) {
        
    }else{
        OtherLoginViewController *otherLogin = [[OtherLoginViewController alloc]init];
        [self.navigationController pushViewController:otherLogin animated:YES];
        [otherLogin release];
    }
}
#pragma mark - 分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _dataArrtop.count;
    }else{
        return _dataArdown.count;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
#pragma mark - 点击每个cell的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            CollectionViewController *collectionVC = [[CollectionViewController alloc]init];
                [self.navigationController pushViewController:collectionVC animated:YES];
                [collectionVC release];
            
        }
        if (indexPath.row == 2) {
            //创建管理器对象
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //获取沙河路径
            NSString *catch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            NSLog(@"%@", NSHomeDirectory());
            if ([fileManager fileExistsAtPath:catch]) {
                NSArray *files = [fileManager subpathsAtPath:catch];
                //遍历所有文件
                for (NSInteger i = 0; i < files.count; i++) {
                    NSString *filePath = [catch stringByAppendingPathComponent:files[i]];
                    //获取文件大小
                    float k = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
                    self.j =  self.j + k;
                    
                }
            }
            NSString *size = [NSString stringWithFormat:@"是否清除%.2fM大小",_j / 1024 / 1024];
            //创建弹窗
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:size preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"取消");
            }];
            [alter addAction:cancle];
            UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"确定");
                //删除整个Caches文件夹
                //            [fileManager removeItemAtPath:catch error:nil];
                self.j = 0;
                //遍历删除Caches文件夹里的每个文件
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                    
                    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                    NSLog(@"files :%lu",(unsigned long)[files count]);
                    for (NSString *p in files) {
                        NSError *error;
                        NSString *path = [cachPath stringByAppendingPathComponent:p];
                        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                        }
                    }
                    UIAlertController *notice = [UIAlertController alertControllerWithTitle:@"提示" message:@"清除缓存成功" preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:notice animated:YES completion:^{
                        //
                    }];
                    [self dismissViewControllerAnimated:YES completion:^{
                        //
                    }];
                    [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
                
            }];
            [alter addAction:yesAction];
            //        [_tableView reloadData];
            //弹出弹窗
            [self presentViewController:alter animated:YES completion:^{
                //
            }];
        }
    }
    if (indexPath.section == 1) {
        //扫一扫
        if (indexPath.row == 0) {
            Scan_VC *scan = [[Scan_VC alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:scan];
            [self presentViewController:nav animated:YES completion:^{
                //
            }];
            [scan release];
        }
        //关于应用
        if (indexPath.row == 1) {
            AboutViewController *aboutVC = [[AboutViewController alloc]init];
            [self.navigationController pushViewController:aboutVC animated:YES];
            [aboutVC release];
        }
        //意见反馈
        if (indexPath.row == 2) {
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
            //打电话
            UIAlertAction *phoneAction = [UIAlertAction actionWithTitle:@"打电话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"打电话");
                NSURL *url = [NSURL URLWithString:@"tel://15140878116"];
                
                [[UIApplication sharedApplication] openURL:url];
                
            }];
            [alter addAction:phoneAction];
            //发邮件
            UIAlertAction *emailAction = [UIAlertAction actionWithTitle:@"发邮件" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //
                // 当点击意见反馈时 调用激活邮件功能
                [self sendMailInApp];
                NSLog(@"发邮件");
            }];
            [alter addAction:emailAction];
            
            //取消
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                //
                NSLog(@"取消");
            }];
            [alter addAction:cancleAction];
            [self presentViewController:alter animated:YES completion:^{
                
            }];
            
        }

    }
}
#pragma mark - 在应用内发送邮件
// 激活邮件功能
- (void)sendMailInApp
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        [self alertWithMessage:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替"];
        return;
    }
    if (![mailClass canSendMail]) {
        [self alertWithMessage:@"用户没有设置邮件账户"];
        return;
    }
    [self displayMailPicker];
}

//调出邮件发送窗口
- (void)displayMailPicker
{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    mailPicker.mailComposeDelegate = self;
    
    //设置主题
    [mailPicker setSubject: @"eMail主题"];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"897204198@qq.com"];
    [mailPicker setToRecipients: toRecipients];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"897204198@163.com", @"third@example.com", nil];
    [mailPicker setCcRecipients:ccRecipients];
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    [mailPicker setBccRecipients:bccRecipients];
    NSString *emailBody = @"我认为这款软件.....正文";
    [mailPicker setMessageBody:emailBody isHTML:YES];
    [self presentViewController:mailPicker animated:YES completion:^{
        
    }];
    [mailPicker release];
}


#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    //关闭邮件发送窗口
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            msg = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            msg = @"用户点击发送，将邮件放到队列中，还没发送";
            break;
        case MFMailComposeResultFailed:
            msg = @"用户试图保存或者发送邮件失败";
            break;
        default:
            msg = @"";
            break;
    }
}

#pragma mark - 清除缓存的方法
-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    
}
#pragma mark - 设置夜间模式set方法
-(void)setNightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    _tableView.backgroundColor = [UIColor blackColor];
//    [SetBlack setBackgroundColorWithView:_tableView];
    
}
-(void)setLightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    _tableView.backgroundColor = [UIColor whiteColor];
//    [SetBlack setBackgroundColorWithView:_tableView];
}
#pragma mark - 设置我的页面各cell中内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Mcell"];
    [SetBlack setCellColorWithCell:cell];
    [SetBlack setLableTitleColorWithArr:@[cell.textLabel]];
    [SetBlack setBackgroundColorWithView:_tableView];
    if (indexPath.section == 0) {
//        if (indexPath.row == 2) {
//            UISwitch *Switch = [[UISwitch alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 60, 10, 50, 20)];
//            Switch.on = [[NSUserDefaults standardUserDefaults]boolForKey:@"message"];;
//            [cell addSubview:Switch];
//            [Switch addTarget:self action:@selector(notClick:) forControlEvents:UIControlEventValueChanged];
//            [Switch release];
//        }else
            if (indexPath.row == 1) {
            UISwitch *kaiguan = [[UISwitch alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 60, 10, 50, 20)];
            kaiguan.on = [BlackManager sharedInstance].isNight;
            [cell addSubview:kaiguan];
            [kaiguan addTarget:self action:@selector(kaiguanAction:) forControlEvents:UIControlEventValueChanged];
            [kaiguan release];
        }else{
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = _dataArrtop[indexPath.row];
            //改变topView的背景颜色
            if ([BlackManager sharedInstance].isNight) {
                self.topview.backgroundColor = [UIColor blackColor];
            }else{
                self.topview.backgroundColor = [UIColor grayColor];
            }
    }
    if (indexPath.section == 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = _dataArdown[indexPath.row];

    }
    //改变topView的背景颜色
    if ([BlackManager sharedInstance].isNight) {
        self.topview.backgroundColor = [UIColor blackColor];
    }else{
        self.topview.backgroundColor = [UIColor grayColor];
    }
        return cell;
}
#pragma mark - 定时器消息推送方法
-(void)switchAction:(UISwitch *)Switch
{
    //本地推送
    //定时器
    self.i = NO;
    _i = [[NSUserDefaults standardUserDefaults]boolForKey:@"message"];
    if (_i) {
        
            [_time invalidate];
            _time = nil;
            //        [_time setFireDate:[NSData distantFuture]];
            //        NSString *notMess = [notification.userInfo objectForKey:@"key"];
        [[UIApplication sharedApplication]cancelAllLocalNotifications];
            [MyselfViewController cancelLocalNotificationWithKey:@"key"];
            [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"message"];
        
    }else{
        
            //创建定时器
            self.time = [NSTimer scheduledTimerWithTimeInterval:10
                                                         target:self selector:@selector(notClick:) userInfo:nil repeats:YES];
            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"message"];
        
    }
}
#pragma mark - 按按钮推送消息
-(void)notClick:(UISwitch *)Switch
{
    if (Switch.on) {
        [MyselfViewController registerLocalNotification:20];// 20秒后
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"message"];
    }else{
        NSLog(@"gfff");
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"message"];
    }
}

// 设置本地通知
+ (void)registerLocalNotification:(NSInteger)alertTime {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
    NSLog(@"fireDate=%@",fireDate);
    
    notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 程序在后台时手机上侧弹出的通知内容
    notification.alertBody =  @"有新的口袋消息了";
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"内容又更新啦" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSDayCalendarUnit;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
// 取消某个本地推送通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key {
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
                
            }
        }
    }
}
#pragma mark - 夜间模式开关
//夜间模式开关
-(void)kaiguanAction:(UISwitch *)kaiguan
{
    if (kaiguan.on) {
        //设置isNight属性的时候就执行set方法 发送夜间还是白天的通知 然后其他页面接到通知执行BaseViewController里的方法
        [BlackManager sharedInstance].isNight = ![BlackManager sharedInstance].isNight;
         self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    }else{
        [BlackManager sharedInstance].isNight = ![BlackManager sharedInstance].isNight;
         self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }
    _tableView.backgroundColor = [UIColor whiteColor];
    [_tableView reloadData];
}
#pragma mark - 改变头像方法
-(void)changeAction
{
    BOOL otherLogin = [[NSUserDefaults standardUserDefaults]boolForKey:@"OtherLogin"];
    if (!otherLogin) {
        //弹窗
        UIAlertController *promptAlert = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        //照相机
        
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //
            NSLog(@"照相机");
            [self cameraAction];
            
        }];
        [promptAlert addAction:cameraAction];
        //相册
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //
            [self pickerAction];
            NSLog(@"相册");
        }];
        [promptAlert addAction:photoAction];
        
        //取消
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //
            NSLog(@"取消");
        }];
        [promptAlert addAction:cancleAction];
        [self presentViewController:promptAlert animated:YES completion:^{
            
        }];
        
    }else{
        //三方登录时不能修改头像
    }
    
    
    
}
#pragma mark - 照相机
-(void)cameraAction
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:^{
            //
        }];
        [picker release];
    }else{
        //如果没有提示用户
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"你没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alter animated:YES completion:^{
            //
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            //
        }];
    }
}
#pragma mark - 相册picker
-(void)pickerAction
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc]init];
    //静态方法判断设备是否支持图库功能
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerImage.delegate = self;
    //是否可编辑 剪裁
    pickerImage.allowsEditing = YES;
    //跳转到相册页面
    [self presentViewController:pickerImage animated:YES completion:^{
        //
    }];
    [pickerImage release];
}
#pragma mark - 相册的协议方法
//相册的协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //将编辑后的图片保存在image中
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //当图片不为空是显示并保存图片
    if (image != nil) {
        _headImg.image = image;
        //以下是保存文件到沙盒路径下
        //把图片转换为NSData类型的数据来保存文件
        NSData *data;
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像
            data = UIImagePNGRepresentation(image);
        }else{
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        //保存
        NSString *picturePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"picture.a"];
        NSNumber *i = [[NSUserDefaults standardUserDefaults]objectForKey:@"index"];
        NSInteger index = i.intValue;
        NSMutableArray *pictureArr = [NSKeyedUnarchiver unarchiveObjectWithFile:picturePath];
        [pictureArr replaceObjectAtIndex:index withObject:data];
        [NSKeyedArchiver archiveRootObject:pictureArr toFile:picturePath];
        //变换后的图片设置为单例显示
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:data forKey:@"img"];
        [self dismissViewControllerAnimated:YES completion:^{
            //
        }];
    }
}




//登陆
-(void)logInAction
{
    BOOL login = [[NSUserDefaults standardUserDefaults]boolForKey:@"register"];
    if (login) {
        NSLog(@"进入管理页面");
        ManagerViewController *manager = [[ManagerViewController alloc]init];
        [self.navigationController pushViewController:manager animated:YES];
        [manager release];
    }else{
    LoginViewController *login = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:login animated:YES];
    [login release];
    NSLog(@"登录");
    }
    
}
//返回按钮方法
-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
